package zhihuilan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import zhihuilan.common.enums.StaticDataEnum;
import zhihuilan.common.utils.ToolsUtils;
import zhihuilan.dto.MyAcquisitionDto;
import zhihuilan.dto.MyStaffShopDto;
import zhihuilan.dto.MyStaffShopGoodsDto;
import zhihuilan.dto.WxMiniPageDto;
import zhihuilan.entity.MyCategoryStaff;
import zhihuilan.entity.MyStaffShop;
import zhihuilan.entity.MySearch;
import zhihuilan.entity.MyStaffShopGoods;
import zhihuilan.mapper.MyCategoryStaffMapper;
import zhihuilan.mapper.MyStaffShopMapper;
import zhihuilan.params.query.MyStaffShopGoodsQueryParam;
import zhihuilan.params.query.MyStaffShopQueryParam;
import zhihuilan.service.MyStaffShopGoodsService;
import zhihuilan.service.MyStaffShopService;
import zhihuilan.service.MySearchService;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户数据 服务实现
 *
 * @author ruoyi
 */
@Service
public class MyStaffShopServiceImpl extends ServiceImpl<MyStaffShopMapper, MyStaffShop> implements MyStaffShopService {

    private final static String tbName = "staff_shop";

    @Resource
    private MySearchService mySearchService;

    @Resource
    private MyStaffShopGoodsService myStaffShopGoodsService;

    @Autowired
    private MyCategoryStaffMapper myCategoryStaffMapper;

    @Override
    public Page<MyStaffShop> selectPageList(MyStaffShopQueryParam queryParam) {
        QueryWrapper<MyStaffShop> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1);
        if (!ObjectUtils.isEmpty(queryParam)) {
            if (!ObjectUtils.isEmpty(queryParam.getStaffId())) {
                queryWrapper.eq("staff_id", queryParam.getStaffId());
            }
        }
        queryWrapper.orderByDesc("create_time");
        long pageNum = 0;
        long pageSize = 10;
        if (queryParam.getPage() >= 0L) {
            pageNum = queryParam.getPage();
        }
        if (queryParam.getPageSize() > 0L) {
            pageSize = queryParam.getPageSize();
        }
        Page<MyStaffShop> page = new Page<>(pageNum, pageSize);
        this.baseMapper.selectPage(page, queryWrapper);
        return page;
    }

    @Override
    public WxMiniPageDto<MyStaffShopDto> selectPageAndGoodsList(MyStaffShopQueryParam queryParam) {
        QueryWrapper<MyStaffShop> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("*", ToolsUtils.getDistanceSqlTencent(queryParam.getLat(), queryParam.getLng()) + " * 1000 as distance ");
        queryWrapper.eq("status", 1);
        if (!ObjectUtils.isEmpty(queryParam)) {
            if (!ObjectUtils.isEmpty(queryParam.getStaffId())) {
                queryWrapper.eq("staff_id", queryParam.getStaffId());
            }
            if (!ObjectUtils.isEmpty(queryParam.getAudit())) {
                queryWrapper.eq("audit", queryParam.getAudit());
            }
            if (!ObjectUtils.isEmpty(queryParam.getType())) {
                queryWrapper.eq("type", queryParam.getType());
            }
            if (!ObjectUtils.isEmpty(queryParam.getLat()) && !ObjectUtils.isEmpty(queryParam.getLng())) {
                queryWrapper.apply(ToolsUtils.getDistanceSqlTencent(queryParam.getLat(), queryParam.getLng()) + " < " + StaticDataEnum.NEAR_100.getKey());
                queryWrapper.orderByAsc(ToolsUtils.getDistanceSqlTencent(queryParam.getLat(), queryParam.getLng()));
            }
        }

        long pageNum = 0;
        long pageSize = 10;
        if (queryParam.getPage() >= 0L) {
            pageNum = queryParam.getPage();
        }
        if (queryParam.getPageSize() > 0L) {
            pageSize = queryParam.getPageSize();
        }
        Page<MyStaffShop> page = new Page<>(pageNum, pageSize);
        this.baseMapper.selectPage(page, queryWrapper);
        WxMiniPageDto<MyStaffShopDto> result = new WxMiniPageDto(page.getCurrent(), page.getSize());
        BeanUtils.copyProperties(page, result);
        List<MyStaffShopDto> convertList = page.getRecords().stream().map(po -> {
            MyStaffShopDto dto = new MyStaffShopDto();
            BeanUtils.copyProperties(po, dto);
            List<MyStaffShopGoodsDto> goodsList = myStaffShopGoodsService.selectPageList(0L, 3L, po.getId());
            dto.setTuiGoods(goodsList);
            return dto;
        }).collect(Collectors.toList());
        result.setData(convertList);
        return result;
    }

    @Override
    public List<MyStaffShopDto> selectList(MyStaffShopQueryParam queryParam) {
        QueryWrapper<MyStaffShop> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1);
        if (!ObjectUtils.isEmpty(queryParam)) {
            if (!ObjectUtils.isEmpty(queryParam.getStaffId())) {
                queryWrapper.eq("staff_id", queryParam.getStaffId());
            }
        }
        queryWrapper.orderByDesc("create_time");
        List<MyStaffShop> selectList = this.baseMapper.selectList(queryWrapper);
        return selectList.stream().map(po -> {
            MyStaffShopDto dto = new MyStaffShopDto();
            BeanUtils.copyProperties(po, dto);
            return dto;
        }).collect(Collectors.toList());
    }

    @Override
    public MyStaffShop selectById(Integer id) {
        if (ObjectUtils.isEmpty(id) || id < 1) {
            return null;
        }
        QueryWrapper<MyStaffShop> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1);
        queryWrapper.eq("id", id);
        return this.baseMapper.selectOne(queryWrapper);
    }
@Override
    public MyStaffShop selectOne(MyStaffShopQueryParam queryParam){
    if (ObjectUtils.isEmpty(queryParam)) {
        return null;
    }
    QueryWrapper<MyStaffShop> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("status", 1);
    queryWrapper.eq("staff_id", queryParam.getStaffId());
    return this.baseMapper.selectOne(queryWrapper);
    }

    @Override
    public MyStaffShopDto selectById(MyStaffShopQueryParam queryParam) {
        if (ObjectUtils.isEmpty(queryParam) || ObjectUtils.isEmpty(queryParam.getId())) {
            return null;
        }
        QueryWrapper<MyStaffShop> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("*", ToolsUtils.getDistanceSqlTencent(queryParam.getLat(), queryParam.getLng()) + " * 1000 as distance ");
        queryWrapper.eq("status", 1);
        queryWrapper.eq("id", queryParam.getId());
        List<MyStaffShop> selectList = this.baseMapper.selectList(queryWrapper);
        List<MyStaffShopDto> dtoList = selectList.stream().map(po -> {
            MyStaffShopDto dto = new MyStaffShopDto();
            BeanUtils.copyProperties(po, dto);
            return dto;
        }).collect(Collectors.toList());
        if (!ObjectUtils.isEmpty(dtoList) && dtoList.size() > 0) {
            return dtoList.get(0);
        }
        return null;
    }


    @Transactional
    @Override
    public MyStaffShop addEntity(MyStaffShop saveEntity) {
        try {
            if (ObjectUtils.isEmpty(saveEntity.getId())) {
                this.baseMapper.insert(saveEntity);
            } else {
                return null;
            }
            return saveEntity;
        } catch (RuntimeException e) {
            throw new RuntimeException("操作失败：" + e.getMessage());
        }
    }

    @Transactional
    @Override
    public MyStaffShop addEntityAndSearch(MyStaffShop saveEntity) {
        try {
            if (ObjectUtils.isEmpty(saveEntity.getId())) {
                this.baseMapper.insert(saveEntity);
            } else {
                return null;
            }
            this.updateMySearchInfo(saveEntity, 1);
            return saveEntity;
        } catch (RuntimeException e) {
            throw new RuntimeException("操作失败：" + e.getMessage());
        }
    }

    @Override
    public MyStaffShop updateEntity(MyStaffShop saveEntity) {
        try {
            if (!ObjectUtils.isEmpty(saveEntity.getId())) {
                this.baseMapper.updateById(saveEntity);
            } else {
                return null;
            }
            return saveEntity;
        } catch (RuntimeException e) {
            throw new RuntimeException("操作失败：" + e.getMessage());
        }
    }

    @Transactional
    @Override
    public MyStaffShop updateEntityAndSearch(MyStaffShop saveEntity) {
        try {
            if (!ObjectUtils.isEmpty(saveEntity.getId())) {
                this.baseMapper.updateById(saveEntity);
            } else {
                return null;
            }
            this.updateMySearchInfo(saveEntity, 2);
            return saveEntity;
        } catch (RuntimeException e) {
            throw new RuntimeException("操作失败：" + e.getMessage());
        }
    }

    @Transactional
    @Override
    public Boolean deleteById(Integer id) {
        try {
            MyStaffShop entity = this.selectById(id);
            if (!ObjectUtils.isEmpty(entity)) {
                this.baseMapper.deleteById(id);
            } else {
                return false;
            }
            return true;
        } catch (RuntimeException e) {
            throw new RuntimeException("操作失败：" + e.getMessage());
        }
    }

    @Transactional
    @Override
    public Boolean deleteByIdAndSearch(Integer id) {
        try {
            MyStaffShop entity = this.selectById(id);
            if (!ObjectUtils.isEmpty(entity)) {
                // 删除商店查询
                this.mySearchService.deleteByTableAndId(tbName, entity.getId());
                // 删除所有商品查询
                this.mySearchService.deleteByTableAndFid("staff_shop_goods", null, entity.getId(), entity.getStaffId());
                QueryWrapper<MyCategoryStaff> queryWrapperCategory = new QueryWrapper<>();
                queryWrapperCategory.eq("pid", id);
                queryWrapperCategory.eq("status", 1);
                queryWrapperCategory.eq("staff_id", entity.getStaffId());
                // 删除对应分类
                this.myCategoryStaffMapper.delete(queryWrapperCategory);
                // 删除对应商品
                myStaffShopGoodsService.deleteByShopId(entity.getId());
                this.baseMapper.deleteById(id);
                return true;
            } else {
                return false;
            }

        } catch (RuntimeException e) {
            throw new RuntimeException("操作失败：" + e.getMessage());
        }
    }

    /**
     * 新增、更新、删除查询表相关信息；
     *
     * @param entity 线缆圈信息
     * @param type   操作类型：1、新增；2、更新；3、删除；
     * @return 返回操作成功或者失败！
     * @author chenk
     * @date 2025年3月4日 15:50:33
     */
    private Boolean updateMySearchInfo(MyStaffShop entity, Integer type) {
        if (type.equals(3)) {
            this.mySearchService.deleteByTableAndId(tbName, entity.getId());
            return true;
        }
        MySearch mySearch = new MySearch();
        mySearch.setStaffId(entity.getStaffId());
        String title = ToolsUtils.replaceCharToSearch(entity.getTitle());
        String content = ToolsUtils.replaceCharToSearch(entity.getIntro());
        mySearch.setName(title);
        mySearch.setContent(content);
        mySearch.setLogo(entity.getLogo());
        mySearch.setTbName(tbName);
        mySearch.setPid(entity.getId());
        mySearch.setType(2);
        mySearch.setUtype(entity.getType());
        mySearch.setLng(entity.getLng());
        mySearch.setLat(entity.getLat());
        mySearch.setRegion(entity.getRegion());
        mySearch.setLnggd(entity.getLnggd());
        mySearch.setLatgd(entity.getLatgd());
        mySearch.setDistrictid(entity.getDistrictid());
        mySearch.setDistrictid1(entity.getDistrictid1());
        mySearch.setDistrictid2(entity.getDistrictid2());
        mySearch.setAddress(!ObjectUtils.isEmpty(entity.getAddress()) ? entity.getAddress() : entity.getRegion());
        mySearch.setCreateTime(Integer.parseInt(new Date().getTime() / 1000 + ""));
        if (type.equals(1)) {
            this.mySearchService.addEntity(mySearch);
        }
        if (type.equals(2)) {
            this.mySearchService.updateEntity(mySearch);
        }
        return true;
    }
}
